import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
import { message } from 'antd';
import { history } from '@umijs/max';
import { deleteEmptyField } from "common/utils/utils";

interface Response {
  code: number
  data: any
  message: string
}

interface CustomRequestConfig {}

const axiosInstance = axios.create({
  timeout: 30000,
  baseURL: '/api',
})

axiosInstance.interceptors.request.use(reqSuccess, reqError);
axiosInstance.interceptors.response.use(resSuccess, resError);

function reqSuccess(config: AxiosRequestConfig & CustomRequestConfig) {
  if(localStorage['token']){
    config.headers!['token'] = localStorage['token'];
  }
  if (config.method && ['get', 'delete'].includes(config.method)) {
    deleteEmptyField(config.params);
  } else if (config.method === 'post') {
    deleteEmptyField(config.data);
  }
  return config;
}

function reqError(error: Error) {
  return Promise.reject(error);
}

function resSuccess(res: AxiosResponse<Response>) {
  const { data } = res;
  if(['blob'].includes(res.config.responseType ?? '')){
    return data;
  }
  if (data.code) {
    message.warning(data.message);
    const error: Omit<AxiosError<Response>, 'isAxiosError' | 'toJSON'> = {
      ...new Error(data.message),
      config: res.config,
      response: res,
    };
    return Promise.reject(error);
  }
  return data.data;
}

function resError(error: AxiosError<Response>) {
  if (error.response) {
    if (error.response.status === 401) {
      message.error('登录超时，请登录');
      history.push('/login');
    } else if (String(error.response.status)[0] === '5') {
      message.error('服务器内部错误，请联系管理员');
    } else if (error.response.status === 400) {
      message.error('请求错误，请联系管理员');
    }
  } else {
    message.error('网络异常，请检查网络');
  }
  return Promise.reject(error);
}

export default <T = any, R = AxiosResponse<T>>(url: string, param: AxiosRequestConfig & CustomRequestConfig): Promise<T> => {
  return axiosInstance.request<T,R>({
    url,
    ...param,
  });
};
